import axios from 'axios';

const API_URL = 'http://localhost:3000/api/models';

// 模拟API响应 - 当后端API不可用时使用
const useMockApi = false; // 使用真实API，与fileService.js保持一致

// 控制台打印API模式
console.log('模型服务正在使用' + (useMockApi ? '模拟API' : '真实API') + '模式');

// 模拟数据
const mockModels = [
    {
        id: '1',
        name: '现代沙发模型',
        description: '一个适合现代风格室内的沙发3D模型',
        createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
        geometry: {
            type: 'cube',
            color: '#FF5733',
            dimensions: {
                width: 2,
                height: 1,
                depth: 3
            },
            position: { x: 0, y: 0, z: 0 },
            rotation: { x: 0, y: 0, z: 0 }
        }
    },
    {
        id: '2',
        name: '办公桌模型',
        description: '简约风格的办公桌，带有抽屉和键盘托架',
        createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(),
        geometry: {
            type: 'cube',
            color: '#3366FF',
            dimensions: {
                width: 4,
                height: 2,
                depth: 2
            },
            position: { x: 0, y: 0, z: 0 },
            rotation: { x: 0, y: 0, z: 0 }
        }
    },
    {
        id: '3',
        name: '装饰球',
        description: '现代装饰球体，适合室内摆设',
        createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(),
        geometry: {
            type: 'sphere',
            color: '#33CC99',
            dimensions: {
                radius: 1,
                segments: 32
            },
            position: { x: 0, y: 0, z: 0 },
            rotation: { x: 0, y: 0, z: 0 }
        }
    },
    {
        id: '4',
        name: '导入的外部模型',
        description: '从外部导入的3D模型',
        createdAt: new Date().toISOString(),
        geometry: {
            type: 'external_model',
            color: '#22AAFF',
            file: 'sample.obj',
            format: 'obj',
            position: { x: 0, y: 0, z: 0 },
            rotation: { x: 0, y: 0, z: 0 },
            scale: { x: 1, y: 1, z: 1 },
            properties: ['file', 'color', 'material', 'position', 'rotation', 'scale'],
            material: { color: '#22AAFF' },
            serverModelId: 'sample-model-123',
            serverModelUrl: 'data:model/obj;base64,',
            metadata: {
                externalId: 'ext-obj-123',
                cacheId: 'ext-obj-123',
                originalType: 'external_model'
            }
        },
        externalModels: [
            {
                id: 'ext-obj-123',
                format: 'obj',
                name: '示例模型',
                fileName: 'sample.obj',
                position: { x: 0, y: 0, z: 0 },
                rotation: { x: 0, y: 0, z: 0 },
                scale: { x: 1, y: 1, z: 1 },
                color: '#22AAFF',
                cacheId: 'ext-obj-123',
                properties: ['file', 'color', 'material', 'position', 'rotation', 'scale']
            }
        ]
    }
];

// 获取所有模型
const getModels = async () => {
    try {
        console.log('[modelService] 开始获取所有模型');
        if (useMockApi) {
            console.log('[modelService] 使用模拟API获取模型');
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 300));
            // 返回模拟数据
            return { data: mockModels };
        }

        console.log('[modelService] 调用真实API获取模型');
        const token = localStorage.getItem('token');
        const response = await axios.get(API_URL, {
            headers: {
                'Authorization': token ? `Bearer ${token}` : undefined
            }
        });
        console.log('[modelService] 成功获取模型, 数量:', response.data?.length);
        return response.data;
    } catch (error) {
        console.error('[modelService] 获取模型失败:', error);
        throw error;
    }
};

// 获取一个模型
const getModel = async (id) => {
    try {
        console.log('[modelService] 开始获取模型:', id);
        if (useMockApi) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 300));

            // 查找模型
            const model = mockModels.find(m => m.id === id);
            if (!model) {
                console.log('[modelService] 模型未找到:', id);
                throw new Error('模型未找到');
            }

            console.log('[modelService] 找到模型:', id);
            return { data: model };
        }

        console.log('[modelService] 调用真实API获取模型:', id);
        const token = localStorage.getItem('token');
        const response = await axios.get(`${API_URL}/${id}`, {
            headers: {
                'Authorization': token ? `Bearer ${token}` : undefined
            }
        });
        console.log('[modelService] 成功获取模型:', id);
        return response.data;
    } catch (error) {
        console.error('[modelService] 获取模型失败:', id, error);
        throw error;
    }
};

// 创建模型
const createModel = async (modelData) => {
    try {
        console.log('[modelService] 开始创建模型:', modelData.name);

        if (useMockApi) {
            console.log('[modelService] 使用模拟API创建模型');
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 500));

            // 创建新模型
            const newModel = {
                id: `model-${Date.now()}`,
                ...modelData,
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            };

            // 添加到模拟数据
            mockModels.push(newModel);

            console.log('[modelService] 模型创建成功:', newModel.id);
            return {
                status: 201,
                data: {
                    status: 201,
                    message: '模型创建成功',
                    data: newModel
                }
            };
        }

        console.log('[modelService] 调用真实API创建模型');
        const token = localStorage.getItem('token');
        const response = await axios.post(API_URL, modelData, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : undefined
            }
        });

        console.log('[modelService] 模型创建成功:', response.data);
        return response;
    } catch (error) {
        console.error('[modelService] 创建模型失败:', error);
        throw error;
    }
};

// 更新模型
const updateModel = async (modelId, modelData) => {
    try {
        console.log('[modelService] 开始更新模型', modelId);
        console.log('[modelService] 更新数据:', JSON.stringify(modelData, null, 2));

        if (useMockApi) {
            console.log('[modelService] 使用模拟API更新模型');
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 500));

            const modelIndex = mockModels.findIndex(model => model.id === modelId);
            if (modelIndex !== -1) {
                console.log('[modelService] 找到要更新的模型:', modelId);

                // 特殊处理几何体和额外几何体
                if (modelData.geometry) {
                    console.log('[modelService] 更新主几何体:', modelData.geometry.type);
                    mockModels[modelIndex].geometry = modelData.geometry;
                }

                // 确保additionalObjects作为一个独立的数组被保存
                if (Array.isArray(modelData.additionalObjects)) {
                    console.log('[modelService] 更新额外几何体, 数量:', modelData.additionalObjects.length);
                    console.log('[modelService] 额外几何体类型:', modelData.additionalObjects.map(obj => obj.type));
                    mockModels[modelIndex].additionalObjects = modelData.additionalObjects;
                }

                // 添加对外部模型的支持
                if (Array.isArray(modelData.externalModels)) {
                    console.log('[modelService] 更新外部模型, 数量:', modelData.externalModels.length);
                    mockModels[modelIndex].externalModels = modelData.externalModels;
                }

                // 处理其他基本字段
                if (modelData.name) {
                    console.log('[modelService] 更新模型名称:', modelData.name);
                    mockModels[modelIndex].name = modelData.name;
                }
                if (modelData.description) {
                    console.log('[modelService] 更新模型描述');
                    mockModels[modelIndex].description = modelData.description;
                }

                console.log('[modelService] 模型更新完成, 最终数据:',
                    '主几何体:', mockModels[modelIndex].geometry.type,
                    '额外几何体数量:', (mockModels[modelIndex].additionalObjects || []).length
                );

                return {
                    status: 200,
                    message: "模型信息更新成功",
                    data: {
                        id: modelId,
                        additionalObjectsCount: (mockModels[modelIndex].additionalObjects || []).length
                    }
                };
            }

            console.log('[modelService] 模型不存在:', modelId);
            throw new Error(JSON.stringify({ status: 404, message: "模型不存在" }));
        }

        console.log('[modelService] 调用真实API更新模型');
        // 确保发送到服务器的数据是正确的
        console.log('[modelService] 发送到API的数据:',
            '主几何体类型:', modelData.geometry?.type,
            '额外几何体数量:', (modelData.additionalObjects || []).length
        );

        const token = localStorage.getItem('token');
        const response = await axios.put(`${API_URL}/${modelId}`, modelData, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : undefined
            }
        });

        console.log('[modelService] API更新成功, 响应:', response.data);
        return response.data;
    } catch (error) {
        console.error('[modelService] 更新模型失败:', error);
        throw error.response?.data || error;
    }
};

// 删除模型
const deleteModel = async (modelId) => {
    console.log('服务层: 准备删除模型', modelId, '类型:', typeof modelId);

    if (!modelId) {
        console.error('错误: 尝试删除模型时缺少模型ID');
        throw new Error('删除模型失败: 没有提供模型ID');
    }

    // 确保ID是字符串
    const id = String(modelId);
    console.log('处理后的模型ID:', id);

    try {
        if (useMockApi) {
            console.log('使用模拟API删除模型:', id);
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 800));

            // 查找方式改进：尝试使用多种方式匹配ID
            let modelIndex = mockModels.findIndex(model =>
                String(model.id) === id ||
                String(model._id) === id
            );

            // 如果没找到，尝试匹配部分ID（针对长ID的情况）
            if (modelIndex === -1 && id.length > 10) {
                console.log('尝试匹配部分ID');
                modelIndex = mockModels.findIndex(model => {
                    const modelId = String(model.id || model._id);
                    return modelId.includes(id.substring(0, 10)) ||
                        id.includes(modelId.substring(0, 10));
                });
            }

            console.log(`模拟删除模型: 查找索引 ${modelIndex} (模型ID: ${id})`);

            if (modelIndex !== -1) {
                const deletedModel = mockModels.splice(modelIndex, 1)[0];
                console.log('模拟删除模型成功:', deletedModel);

                return {
                    status: 200,
                    message: "模型已删除",
                    data: { id: id }
                };
            }

            // 如果仍然找不到但ID看起来有效，假设删除成功
            if (id.length > 10) {
                console.log('模型在模拟数据中不存在，但假设删除成功');
                return {
                    status: 200,
                    message: "模型已删除",
                    data: { id: id }
                };
            } else {
                console.error('无效的模型ID格式');
                throw new Error('无效的模型ID格式');
            }
        }

        console.log(`发送删除请求到: ${API_URL}/${id}`);
        const response = await axios.delete(`${API_URL}/${id}`, {
            headers: {
                Authorization: `Bearer ${localStorage.getItem('token')}`
            }
        });
        console.log('删除模型API响应:', response.data);
        return response.data;
    } catch (error) {
        console.error('删除模型失败:', error);

        // 提取更有用的错误信息
        let errorMessage;
        if (error.response) {
            // 服务器响应了错误状态码
            errorMessage = `服务器错误 (${error.response.status}): ${error.response.data?.message || 'Unknown error'}`;
        } else if (error.request) {
            // 请求发送但没有收到响应
            errorMessage = '无法连接到服务器，请检查网络连接';
        } else {
            // 请求设置过程中出错
            errorMessage = error.message || '删除模型时出现未知错误';
        }

        const enhancedError = new Error(errorMessage);
        enhancedError.originalError = error;
        throw enhancedError;
    }
};

// 获取几何体类型
const getGeometryTypes = async () => {
    try {
        if (useMockApi) {
            console.log('使用模拟API获取几何体类型');
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 300));

            return {
                status: 200,
                data: [
                    { id: 'cube', name: '立方体', description: '三维方块几何体' },
                    { id: 'sphere', name: '球体', description: '球形几何体' },
                    { id: 'cylinder', name: '圆柱体', description: '圆柱形几何体' },
                    { id: 'cone', name: '圆锥体', description: '圆锥形几何体' },
                    { id: 'plane', name: '平面', description: '二维平面几何体' }
                ]
            };
        }

        const response = await axios.get(`${API_URL}/geometry-types`, {
            headers: {
                Authorization: `Bearer ${localStorage.getItem('token')}`
            }
        });
        return response.data;
    } catch (error) {
        console.error('获取几何体类型失败:', error);
        throw error.response?.data || error;
    }
};

// 辅助函数 - 将RGB颜色转换为HEX
const rgbToHex = (r, g, b) => {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};

// 辅助函数 - 将HEX颜色转换为RGB
const hexToRgb = (hex) => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
};

// 导出服务及辅助函数
const modelService = {
    getModels,
    getModel,
    createModel,
    updateModel,
    deleteModel,
    getGeometryTypes,
    rgbToHex,
    hexToRgb,
    useMockApi
};

export default modelService;